package ro.gateway.aida.struts.action.listers;

import java.util.Iterator;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import ro.gateway.aida.db.PersistenceManager;
import ro.gateway.aida.db.PersistenceToken;
import ro.gateway.aida.obj.Country;
import ro.gateway.aida.obj.db.CountryDB;
import ro.gateway.aida.struts.MultiTilesAction;
import ro.gateway.aida.struts.form.CountryFilterForm;
import ro.gateway.aida.usr.Arbiter;
import ro.gateway.aida.usr.Perms;
import ro.gateway.aida.usr.User;
import ro.gateway.aida.usr.UserDB;
import ro.gateway.aida.usr.UserUtils;
import ro.gateway.aida.utils.PageToken;
import ro.gateway.aida.utils.SortedList;
import ro.gateway.aida.utils.Utils;
import ro.xblue.translator.TranslatorUtils;


/*
 * Created on 08.01.2004
 * Local Projects Database
 * Mihai Postelnicu (mihai@ro-gateway.org)
 * (c) 2003 by eRomania Gateway
 */

/**
 * @author Mihai Postelnicu<p>
 *
 *  e-mail (mihai@ro-gateway.org)<br>
 * (c) 2003 by eRomania Gateway<p>
 */
public class ListUsersAction extends MultiTilesAction {
    private UserDB udb;
    private CountryDB cdb;
    private Arbiter ar;

    public ActionForward modeSelect(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response)
        throws Exception {
        String mode = request.getParameter("mode");

        if (mode == null)
            mode = (String) request.getAttribute("mode");

		Utils.setBreadCrumbs(request,"bc.userexp");

        if ("refresh".equals(mode))
            return modeRefresh(mapping, form, request, response);
          
		if ((mode != null) && mode.matches("[a-z]*Sort"))
					   return modeSort(mapping, form, request, response);
            
		if (request.getParameter("filter") != null)
							  return modeFilter(mapping, form, request, response);

		if (request.getParameter("csv_list")!=null)
			return csvExport(mapping, form, request, response);
						
        return modeView(mapping, form, request, response);
    }
    
	public ActionForward modeFilter(ActionMapping mapping, ActionForm form,
			   HttpServletRequest request, HttpServletResponse response)
			   throws Exception {
			   CountryFilterForm cff = (CountryFilterForm) form;
			   HttpSession session = request.getSession();
			   String lang = TranslatorUtils.getCurrentLanguage(request, sc)
											.getLanguage();

			   SortedList sl = (SortedList) session.getAttribute(LIST);
        
			   //the filter
			   sl=udb.getAll();
			   sl.setComparator(new User.NameComparator());
			   if (!cff.getIso3().equals("ALL")) {
				   Iterator i=sl.iterator();
							   while (i.hasNext()) {
					   User o = (User) i.next();
					   if ((o.getCountry_iso3().equals(cff.getIso3())))
						   o.setSelected(true);
				   }
				   SortedList sl2=new SortedList();
				   i=sl.iterator();
				   while (i.hasNext()) {
					User element = (User) i.next();
					   if (element.isSelected()) sl2.add(element);
				   }
				   sl=sl2;    
			   }
			   session.setAttribute(LIST,sl);
			  
			   PageToken.tokenizeList( request,  sc, sl, "users");
			   
			   return mapping.getInputForward();
		   }
    
    
	public ActionForward csvExport(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
				
				return mapping.findForward("csvexport");
				
			}

    public ActionForward modeSort(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response)
        throws Exception {
        HttpSession session = request.getSession();
        SortedList sl = (SortedList) session.getAttribute(LIST);
        String lang = TranslatorUtils.getCurrentLanguage(request, sc)
                                     .getLanguage();
        String mode = request.getParameter("mode");

        if ("nameSort".equals(mode))
            sl.setComparator(new User.NameComparator());

        if ("emailSort".equals(mode))
            sl.setComparator(new User.EmailComparator());
            
		if ("countrySort".equals(mode))
					  sl.setComparator(new User.CountryComparator());

		PageToken.tokenizeList( request,  sc, sl, "users");
        
        return mapping.getInputForward();
    }

    public ActionForward modeRefresh(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response)
        throws Exception {
        HttpSession session = request.getSession();
        String lang = TranslatorUtils.getCurrentLanguage(request, sc)
                                     .getLanguage();

        session.setAttribute(LIST, udb.getAll());

        SortedList sl = (SortedList) session.getAttribute(LIST);

        PageToken.tokenizeList( request,  sc, sl, "users");
        
        return mapping.getInputForward();
    }

    public ActionForward modeView(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response)
        throws Exception {
        HttpSession session = request.getSession();

        SortedList users = (SortedList) session.getAttribute(LIST);
        PageToken.tokenizeList( request,  sc, users, "users");
        return mapping.getInputForward();
    }

    public ActionForward modePrepare(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response)
        throws Exception {
        String lang = TranslatorUtils.getCurrentLanguage(request, sc)
                                     .getLanguage();
        PersistenceToken token = PersistenceManager.tokenLookup(sc);
        udb = UserDB.getManager(token);
        ar = Arbiter.getManager(token);
        cdb = CountryDB.getManager(token);

        HttpSession session = request.getSession();

        if (UserUtils.getLogged(request, response) == null)
            return mapping.findForward("plslogin");

        if (!ar.canDo(request, Perms.ADMIN_TOOLS))
            return mapping.findForward("norights");
            
		
		if (session.getAttribute(Country.LIST) == null)
				session.setAttribute(Country.LIST, cdb.getCountries());


        SortedList sl = (SortedList) session.getAttribute(LIST);

        if (sl == null)
            request.setAttribute("mode", "refresh");

        return modeSelect(mapping, form, request, response);
    }
	public static final String LIST = "adminUsers_LIST";
}
